package com.longshihan.testplugin.asm;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * Created by LONGHE001.
 *
 * @time 2019/7/8 0008
 * @des
 * @function
 */

public class LifecycleClassVisitor extends ClassVisitor implements Opcodes {
    private String mClassName;
    private int fAcc;
    private String fName;
    private String fDesc;
    private boolean isInterface;
    private int access;


    public LifecycleClassVisitor(ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        this.mClassName = name;
        isInterface = (access & ACC_INTERFACE) != 0;
        System.out.println(name + " extends " + superName + " {");
        super.visit(version, access, name, signature, superName, interfaces);
    }

    @Override
    public void visitEnd() {
        System.out.println("}");
        if (!isInterface) {
            FieldVisitor fv = cv.visitField(ACC_PUBLIC + ACC_STATIC, "timer", "J", null, null);
            if (fv != null) {
                fv.visitEnd();
            }
        }
        super.visitEnd();
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        System.out.println(" " + name+":::::" + desc);
        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        //匹配FragmentActivity
        if ("onCreate".equals(name)) {
            //处理onCreate
            return new LifecycleOnCreateMethodVisitor(mv);
        } else if ("onDestroy".equals(name)) {
            //处理onDestroy
            return new LifecycleOnDestroyMethodVisitor(mv);
        }else if ("testPlugin0".equals(name)){
            return new TimeMethodVisitor(mv,mClassName);
        }else if ("testPlugin1".equals(name)){
            return new AddTimerMethodAdapter6(access,name,desc,mv);
        }
        return mv;
    }

    @Override
    public void visitSource(String source, String debug) {
        super.visitSource(source, debug);
    }

    @Override
    public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
        System.out.println(" " + desc + " " + name);
        return super.visitField(access, name, desc, signature, value);
    }
}
